package com.jl.code.controller;

import com.jl.code.entity.User;
import com.jl.code.entity.WeiXinUser;
import com.jl.code.service.UserService;
import com.jl.pojo.WeixinOauth2Token;
import com.jl.util.AdvancedUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
public class WeiXinController {


    @Autowired
    private UserService userService;


    /**
     * 跳转页面 进行网页授权                                                                     http://39.105.65.69/text1
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx41c9f671d9c6355f&redirect_uri=http%3a%2f%2f39.105.65.69%2ftext1&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
     * @return
     */
    @RequestMapping("/text1")
    public String text1(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {

        request.setCharacterEncoding("gb2312");
        response.setCharacterEncoding("gb2312");

        //用户同意授权
        String code =request.getParameter("code");

        //用户同意授权要跳转的页面
        if(!"authdeny".equals(code)){

            WeixinOauth2Token weixinOauth2Token= AdvancedUtil.getOauth2Token("","",code);

            //网页授权凭证
            String accessToken=weixinOauth2Token.getAccessToken();
            //用户的标识
            String openId=weixinOauth2Token.getOpenId();

            WeiXinUser weiXinUser=AdvancedUtil.getWeiXinUser(accessToken,openId);

            System.out.println("-------------------------------"+weiXinUser.getOpenId());


            //将weiXinUser保存在数据库里面，或者于数据库里面的信息进行比对，看看是否存在。


            return "index";

        }

        //用户不同意授权的页面
        return "error";


    }


    @RequestMapping("text11")
    public String text(){

        List<User> users=userService.findAll();

        System.out.println("---------------"+users);

        return null;


    }




}
